# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import MySQLdb
import hashlib
class ZggangcaiPipeline(object):
    def open_spider(self,spider):
        self.db=MySQLdb.connect(port=3306,
                                host='127.0.0.1',
                                db='test',
                                user='root',
                                passwd='mysql',
                                charset='utf8')
        self.cur=self.db.cursor()

    def process_item(self, item, spider):
        md_=''
        for data in item.values():
            md_+=data
        md_5=hashlib.md5()
        md_5.update(md_)
        md_=md_5.hexdigest()
        sql="""select md_ from gangcai where md_=%s"""
        try:
            self.cur.execute(sql,[md_])
        except MySQLdb.MySQLError as f:
            print f

        print self.cur.fetchall()
        if self.cur.fetchall() == ():
            sql="""insert into gangcai(md_,addr,area,time_1,name_1,formatr_1,material,src,price)
                   values(%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
            try:
                self.cur.execute(sql,
                                 [md_,
                                  item['addr'],
                                  item['area'],
                                  item['time_1'],
                                  item['name_1'],
                                  item['formatr_1'],
                                  item['material'],
                                  item['src'],
                                  item['price'],
                                  ])
            except MySQLdb.MySQLError as f:
                print f
            self.db.commit()
        return item
    def close_spider(self,spider):
        self.db.close()